﻿using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;

namespace TestUdpDemo;

/// <summary>
///     Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private bool _isListening;
    private readonly DispatcherTimer _statusTimer=new();
    private UdpClient? _udpReceiver;

    public MainWindow()
    {
        InitializeComponent();
        InitializeStatusTimer();
        UpdateStatus("就绪 - 请点击启动监听开始UDP通信");
    }

    private void InitializeStatusTimer()
    {
        _statusTimer.Interval = TimeSpan.FromSeconds(2);
        _statusTimer.Tick += (s, e) => UpdateConnectionStatus();
    }

    private void btnStart_Click(object sender, RoutedEventArgs e)
    {
        if (_isListening)
        {
            StopListening();
            btnStart.Content = "启动监听";
            UpdateStatus("已停止监听");
        }
        else
        {
            if (int.TryParse(txtLocalPort.Text, out var localPort))
            {
                StartListening(localPort);
                btnStart.Content = "停止监听";
                _statusTimer.Start();
            }
            else
            {
                MessageBox.Show("请输入有效的本地端口号");
            }
        }
    }

    private void StartListening(int port)
    {
        try
        {
            _udpReceiver = new UdpClient(new IPEndPoint(IPAddress.Any, port));
            _isListening = true;

            UpdateStatus($"正在监听端口 {port}...");
            AddLog($"=== UDP监听已启动 (端口: {port}) ===");

            // 开始异步接收消息
            Task.Run(async () => await ReceiveMessagesAsync());
        }
        catch (Exception ex)
        {
            MessageBox.Show($"启动监听失败: {ex.Message}");
            _isListening = false;
        }
    }

    private void StopListening()
    {
        _isListening = false;
        _udpReceiver?.Close();
        _statusTimer.Stop();
        AddLog("=== UDP监听已停止 ===");
    }

    private async Task ReceiveMessagesAsync()
    {
        while (_isListening && _udpReceiver != null)
            try
            {
                var result = await _udpReceiver.ReceiveAsync();
                var message = Encoding.UTF8.GetString(result.Buffer);
                var remoteEndpoint = $"{result.RemoteEndPoint.Address}:{result.RemoteEndPoint.Port}";

                // 在UI线程上更新界面
                Dispatcher.Invoke(() => { AddLog($"[接收来自 {remoteEndpoint}] {message}"); });
            }
            catch (ObjectDisposedException)
            {
                // UdpClient已被释放，正常退出
                break;
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => AddLog($"[接收错误] {ex.Message}"));
                break;
            }
        
        Console.WriteLine("Exited ReceiveMessagesAsync loop");
    }

    private async void btnSend_Click(object sender, RoutedEventArgs e)
    {
        await SendMessage();
    }

    private async void txtMessage_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            await SendMessage();
            e.Handled = true;
        }
    }

    private async Task SendMessage()
    {
        var message = txtMessage.Text.Trim();
        if (string.IsNullOrEmpty(message)) return;

        if (!IPAddress.TryParse(txtRemoteIP.Text, out var remoteIP))
        {
            MessageBox.Show("请输入有效的远程IP地址");
            return;
        }

        if (!int.TryParse(txtRemotePort.Text, out var remotePort))
        {
            MessageBox.Show("请输入有效的远程端口号");
            return;
        }

        try
        {
            IPEndPoint remoteEp = new IPEndPoint(remoteIP, remotePort);
            var bytes = Encoding.UTF8.GetBytes(message);
            await _udpReceiver!.SendAsync(bytes, bytes.Length, remoteEp);

            AddLog($"[发送到 {remoteIP}:{remotePort}] {message}");
        }
        catch (Exception ex)
        {
            MessageBox.Show($"发送失败: {ex.Message}");
        }
    }

    private void AddLog(string message)
    {
        var timestamp = DateTime.Now.ToString("HH:mm:ss");
        txtLog.AppendText($"[{timestamp}] {message}\n");
        txtLog.ScrollToEnd();
    }

    private void UpdateStatus(string status)
    {
        txtStatus.Text = $"状态: {status}";
    }

    private void UpdateConnectionStatus()
    {
        var status = _isListening ? $"监听中 - 本地端口: {txtLocalPort.Text}" : "未监听";
        UpdateStatus(status);
    }

    protected override void OnClosed(EventArgs e)
    {
        StopListening();
        base.OnClosed(e);
    }
}